﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace MOAWebService.WebService
{
    /// <summary>
    /// JqueryService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/", Description = "jquery交互服务")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    [System.Web.Script.Services.ScriptService]
    public class JqueryService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        #region 通用后台调用方法
        /// <summary>
        /// 通用后台调用方法
        /// </summary>
        /// <param name="asb"></param>
        /// <param name="cls"></param>
        /// <param name="mth"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public string AjaxMethod(string asb, string cls, string mth, string param)
        {
            //此方法如果传入的param中的表是一个select语句，则会存在bug
            asb = AssemblyName(asb);
            string assemblyName = asb;
            string fullName = asb;

            //不为空则默认在根目录
            if (!string.IsNullOrEmpty(cls))
            {
                fullName += "." + cls;
            }
            var bllType = Assembly.Load(assemblyName).GetType(fullName);

            var methodName = mth;
            var _method = bllType.GetMethod(methodName);

            if (null != _method)
            {
                var _parameters = _method.GetParameters();
                string[] parameterValues = param.Split(',');
                for (int i = 0; i < parameterValues.Length; i++)
                {
                    parameterValues[i] = ParamChange(Server.UrlDecode(parameterValues[i]));
                }

                var instance = Activator.CreateInstance(bllType);
                var result = _method.ReturnType == typeof(void) ? "{}" : _method.Invoke(instance, parameterValues).ToString();
                //以上Invoke省略了判断以及捕捉异常
                return result;
            }
            return "系统找不到后台方法";
        }


        /// <summary>
        /// 通用后台调用方法
        /// </summary>
        /// <param name="asb"></param>
        /// <param name="cls"></param>
        /// <param name="mth"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public string AjaxMethodJson(string asb, string cls, string mth, string param)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();

            asb = AssemblyName(asb);
            Dictionary<string, object> myparams = (Dictionary<string, object>)js.DeserializeObject(param);
            string assemblyName = asb, fullName = asb + "." + cls;
            Type bllType = Assembly.Load(assemblyName).GetType(fullName);

            string methodName = mth;
            MethodInfo _method = bllType.GetMethod(methodName);

            if (null != _method)
            {
                ParameterInfo[] _parameters = _method.GetParameters();
                object[] parameterValues = new object[_parameters.Length];
                for (int j = 0; j < _parameters.Length; j++)
                {
                    string funParam = _parameters[j].Name;
                    foreach (KeyValuePair<string, object> keyV in myparams)
                    {
                        string requestParam = keyV.Key;
                        if (funParam.ToLower() == requestParam.ToLower())
                        {
                            //默认集合类型数据不转换
                            if (keyV.Value.GetType().FullName == "System.Object[]")
                            {
                                parameterValues[j] = keyV.Value;
                            }
                            else//常规参数才转化为字符串
                            {
                                parameterValues[j] = ParamChange(keyV.Value.ToString());
                            }
                            break;
                        }
                    }
                }

                object instance = Activator.CreateInstance(bllType);
                object result = _method.ReturnType == typeof(void) ? "{}" : _method.Invoke(instance, parameterValues).ToString();
                //以上Invoke省略了判断以及捕捉异常
                return result.ToString();
            }
            return "系统找不到后台方法";
        }

        //获取命名空间全称（根据命名空间缩写字母获得）
        private string AssemblyName(string name)
        {
            string AllName = name;
            if (string.IsNullOrEmpty(AllName))
            {
                AllName = "Business";
            }
            switch (name.ToLower())
            {
                case "b":
                    AllName = "Business";
                    break;
                case "c":
                    AllName = "Common";
                    break;
                case "m":
                    AllName = "MapBusiness";
                    break;
                case "s":
                    AllName = "SbBusiness";
                    break;
                case "w":
                    AllName = "WF_Business";
                    break;
            }
            return AllName;
        }

        //参数转换
        [WebMethod(EnableSession = true)]
        public string ParamChange(string param)
        {
            string parameterValues = param;
            switch (param.ToUpper())
            {
                case "{DICTPATH}":
                    parameterValues = HttpContext.Current.Server.MapPath("../../");
                    break;
                default:
                    if (Session[param] != null)
                    {
                        parameterValues = Session[param].ToString();
                    }
                    break;
            }
            return parameterValues;
        }

        #endregion
    }
}
